package com.example.demo.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class FileUtil {


    public static String uploadFile(MultipartFile file, String filePath) throws Exception {
        File targetFile = new File(filePath);
        //获取客户机的原文件名
        String fileName = file.getOriginalFilename();
        String newFileName = renameToUUID(fileName);
        //路径不存在则创建一个文件夹
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + newFileName);
        out.write(file.getBytes());
        out.flush();
        out.close();
        return fileName;
    }
    public static String renameToUUID(String fileName) {
        return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
    }


    public static List<String> getFileNamesFromDir(String path){
        List<String> fns = new ArrayList<String>();
        String[] list=new File(path).list();
        for(int i=0;i<list.length;i++){
            fns.add(list[i]);
        }
        return fns;
    }

    public static void downloadFile(String filepath, String filename,
                                    HttpServletResponse response) throws IOException {
        File file = new File(filepath + "/" + filename);
        if (file.exists()) { //判断文件是否存在
            //创建输入对象
            FileInputStream fis = new FileInputStream(file);
            response.setContentType("application/force-download;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);
            OutputStream os = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while (len != -1) {
                len = fis.read(buf);
                os.write(buf, 0, len);
            }
            System.out.println("----------file download---" + filename);
            fis.close();
        }
    }
}
